<?php
/**
 * Created by PhpStorm.
 * User: hengsu
 * Date: 2016/6/2
 * Time: 11:49
 */

namespace Home\Controller;
use Think\Controller;

class LoginController extends Controller{
    public function wechatLog(){
        if(isset($_GET['code'])){
            $surl='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.C('APPID').'&secret='.C('APPSECRET').'&code='.$_GET['code'].'&grant_type=authorization_code';
            $data=$this->https_request($surl);
            $dataObj=json_decode($data);
            $user=M('User');
            $userli=$user->where('openId="'.$dataObj->openid.'"')->find();
            if(empty($userli)){
                $userurl='https://api.weixin.qq.com/sns/userinfo?access_token='.$dataObj->access_token.'&openid='.$dataObj->openid.'&lang=zh_CN';
                $userinfo=file_get_contents($userurl);
                $userinfo=json_decode($userinfo);
                $data=array(
                    'avatar'   =>  $userinfo->headimgurl,
                    'sex'      =>  $userinfo->sex,
                    'nickname' =>  $userinfo->nickname,
                    'openId'   =>  $userinfo->openid,
                    'address'  =>  $userinfo->country.$userinfo->province.$userinfo->city,
                    'reg_time' =>  time()
                );
                $user->add($data);
                $userid=$user->field('id')->where($data)->find();
                $userId=$userid['id'];
                header('location:http://wx.vkaotong.com/exam/index.html?userId='.$userId);
            }else{
                $userId=$userli['id'];
                header('location:http://wx.vkaotong.com/exam/index.html?userId='.$userId);
            }


        }else{
            $rurl=urlencode('http://wx.vkaotong.com/Home/Login/wechatLog');
            $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".C('APPID')."&redirect_uri=".$rurl."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
            header('location:'.$url);
        }
    }
    /**
     * @param $url  请求路径
     * @param null $data   请求参数
     * @return mixed
     */
    private function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}